<script type="text/javascript" src="/js/Emitter.js"></script>
<script>

function WannaCryScan() {
  this.emitter = new Emitter();
}

WannaCryScan.prototype = {
  constructor: WannaCryScan,

  startScan: function (target) {
    this.target = target;
    var thiz = this;
    $.ajax({
      url: "/api/cry",
      data: {
        target: target,
      },
      type: "POST",
      dataType : "json",
    })

    .done(function( json ) {
      thiz.id = json.id;
      setTimeout(function () { pullExec() } , 1000);
      thiz.emitter.emit('start');
    })
    // Code to run if the request fails; the raw request and
    // status codes are passed to the function
    .fail(function( xhr, status, errorThrown ) {
      alert( "Sorry, there was a problem!" );
      console.log( "Error: " + errorThrown );
      console.log( "Status: " + status );
      console.dir( xhr );
    })
  },

  cancelScan: function () {

  },

  on: function (event, callback) {
    this.emitter.on(event, callback);
  },

  analyseResult: function(result) {
    var resultForMan = {};
    var dangerPorts = ["135", "137", "138", "139", "445"];

    resultForMan.host = result.host;
    resultForMan.safe = true;
    //当135,137,138,139,445端口均未打开时，则判定为安全
    var openPorts = result.data[0].openPorts;
    for (var i=0; i<openPorts.length; i++) {
      var p = openPorts[i];
      if (p.state.state != 'open')
        continue;
      if (dangerPorts.indexOf(p.port.portid) != -1)
        resultForMan.safe = false;
    }
    openPorts.sort((a, b)=> {
      return parseInt(a.port.portid) - parseInt(b.port.portid);
    });

    //将危险端口标记出来
    for (var i=0; i<openPorts.length; i++) {
      var p = openPorts[i];
      if (dangerPorts.indexOf(p.port.portid) != -1)
        p.state.danger = true;
    }
    resultForMan.ports = openPorts;
    return resultForMan;
  }
};

var cryScanner = new WannaCryScan();

cryScanner.on('start', () => {
  $("#loading").modal('show');
});

cryScanner.on('end', (result) => {
  $("#loading").modal('hide');
  var resultForMan = cryScanner.analyseResult(result);
  displayResult(resultForMan);
});

cryScanner.on('error', () => {
  $("#loading").modal('hide');
});


$(document).ready(function(){
  $('#viewFixHelp').click(function(){
    window.open("/fixcry.html");
  });
  $('#fix-help').click(function(){
    window.open("/fixcry.html");
  });

  $("#check-me").click(function() {
    cryScanner.startScan("me");
    //cryScanner.emitter.emit('start');
    //cryScanner.emitter.emit('end');
	});

  $("#addrOK").click(function() {
    var addr = $("#other-addr").val();
    if (addr.length == 0)
      return;
    $("#addrModel").modal('hide');
    cryScanner.startScan(addr);
	});

});

function displayResult(result) {
  //显示结果
  var safeText = result.safe ? "安全": "危险";
  $('#safeFlag').text(safeText);
  $('#safeFlag').removeClass("text-safe text-danger");
  if (result.safe) {
    $('#safeFlag').addClass("text-safe");
  } else {
    $('#safeFlag').addClass("text-danger");
  }

  $('#targetAddr').text(result.host);
  $('#idPortTable tbody tr').remove();

/*
  var table = document.getElementById("idPortTable");
  for (var i =  0 , len = result.ports.length; i < len ; i++) {
    var currentRow = table.rows.length;
    var row = table.insertRow(currentRow);
    var cell0 = row.insertCell(0);
    cell0.innerHTML = i+1;

		var portObj = result.ports[i];
    var cell1 = row.insertCell(1);
    cell1.innerHTML = portObj.port.portid;
    var cell2 = row.insertCell(2);
    cell2.innerHTML = portObj.service.name;
    var cell3 = row.insertCell(3);
    cell3.innerHTML = portObj.state.state;
    var cell4 = row.insertCell(4);
    if (portObj.state.danger) {
      cell4.innerHTML = '请关闭';
    }
  }
  */
  for (var i =  0 , len = result.ports.length; i < len ; i++) {
    var portObj = result.ports[i];
    var n = i+1;
    if (portObj.state.danger) {
      var tip = "请关闭";
    }else {
      var tip = "";
    }
    var  trHtml = `<tr><th>${n}</th> <td>${portObj.port.portid}</td> <td>${portObj.service.name}</td> <td>${portObj.state.state}</td> <td>${tip}</td> </tr>`;
    var tr = $(trHtml);
    if (portObj.state.danger) {
      tr.addClass("tr-danger");
    }
    $('#idPortTable tbody:last-child').append(tr);
  }
  $('#cryModal').modal('show');
}

function pullExec() {
  $.ajax({
    url: "/api/cry",
    data: {
      id: cryScanner.id
      },
    type: "GET",
    dataType : "json",
  })

  .done(function( json ) {
    if (json.status == "running") {
      setTimeout(function (){ pullExec() } , 1000);
    } else {
			cryScanner.emitter.emit('end', json);
    }
  })
  // Code to run if the request fails; the raw request and
  // status codes are passed to the function
  .fail(function( xhr, status, errorThrown ) {
    alert( "Sorry, there was a problem!" );
    console.log( "Error: " + errorThrown );
    console.log( "Status: " + status );
    console.dir( xhr );

  })
}

</script>
